package com.example.teesystem.controller;

import cn.hutool.core.lang.Validator;

import cn.hutool.json.JSONUtil;
import com.example.teesystem.common.Permission.PermissionCheck;
import com.example.teesystem.common.cache.CourseCache;
import com.example.teesystem.common.cache.UserCache;
import com.example.teesystem.common.utils.FileUtil;
import com.example.teesystem.common.utils.Response;
import com.example.teesystem.common.utils.ResultCode;
import com.example.teesystem.entity.Course;
import com.example.teesystem.entity.CourseData;
import com.example.teesystem.filter.MyHandlerInterceptor;
import com.example.teesystem.service.CourseDataService;
import com.example.teesystem.service.CourseService;
import com.example.teesystem.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping(value = "/tee/courseData",produces = "application/json; charset = utf-8")
@RequiredArgsConstructor
@Validated


public class CourseDataController {
    private final CourseDataService courseDataService;
    private final HttpServletResponse response;
    private final UserService userService;
    private final CourseService courseService;
    /**
     * 上传资料，UID即为当前用户
     * @param files
     * @param courseId
     * @param title
     * @param message
     * @return
     */
    @ApiOperation("课程资料上传")
    @PostMapping("/upload")
    @Transactional
    public Response uploadData(@RequestParam("file")MultipartFile[] files, @RequestParam("courseId") int courseId,
                               @RequestParam("title") String title, @RequestParam("message") String message){
        int isPublic = 1;
        if(UserCache.userMap.get(MyHandlerInterceptor.getUid()).getType() != 1) {
            return Response.error(ResultCode.COURSE_DATA_UPLOAD_PERMISSION_ERROR.getMsg(),ResultCode.COURSE_DATA_UPLOAD_PERMISSION_ERROR.getCode());
        }
        if(Validator.isNull(files)||Validator.isNull(courseId)||Validator.isNull(isPublic)||Validator.isNull(title)||Validator.isNull(message)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        CourseData courseData = new CourseData(courseId,isPublic,title,message);
        courseData.setUploadId(MyHandlerInterceptor.getUid());
        Course course = CourseCache.courseMap.get(courseData.getCourseId());
        if(course == null){
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        Response response =  FileUtil.UploadFile(files,FileUtil.FILE_PATH+FileUtil.DATABASE+courseData.getCourseId()+"/");
        if(response.get("data") == null){
            return Response.error(ResultCode.FILE_UPLOAD_ERROR);
        }
        String url = (String) ((Map) response.get("data")).get("url");
        courseData.setUrl(url);
        courseDataService.save(courseData);
        return Response.ok();
    }

    /**
     * 下载课程资料
     * @param map
     * @return
     */
    @ApiOperation("课程资料下载")
    @PostMapping("/download")
    public Response downloadData(@RequestBody Map<String, String> map){
        String fileUrl = map.get("fileUrl");
        if(Validator.isNull(fileUrl)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        String file = "";
        return FileUtil.downloadFileByWeb(fileUrl,response);
    }


    /**
     * 删除个人上传的资料
     * @param map
     * @return
     */
    @PostMapping("/PersonalRemove")
    public Response PersonalRemove(@RequestBody(required = false)Map<String, Integer> map){
        int Id = map.get("Id");
        if(Validator.isNull(Id)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        CourseData courseData = courseDataService.getById(Id);
        if(courseData == null) {
            return Response.error(ResultCode.COURSE_DATA_NOT_FOUND_ERROR.getMsg(),ResultCode.COURSE_DATA_NOT_FOUND_ERROR.getCode());
        }
        if(courseData.getUploadId() != MyHandlerInterceptor.getUid()) {
            return Response.error(ResultCode.COURSE_DATA_REMOVE_PERMISSION_ERROR.getMsg(),ResultCode.COURSE_DATA_REMOVE_PERMISSION_ERROR.getCode());
        }
        return courseDataService.remove(Id);
    }

    /**
     * 教师强制删除任何资料
     * @param map
     * @return
     */
    @PostMapping("/ForceRemove")
    public Response ForceRemove(@RequestBody(required = false)Map<String, Integer> map){
        int Id = map.get("Id");
        if(Validator.isNull(Id)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        return courseDataService.remove(Id);
    }

    /**
     * 老师获取某课程下所有资料，当主管教师使用isPublic=0指令查询时，将显示所有资料，包括私密资料
     * @param map
     * @return
     */
    @ApiOperation("获取某一课程下的所有资料")
    @PostMapping("/getCourseDataList")
    public Response getCourseDataList(@Valid @RequestBody(required = false) Map<String, Object> map) {
        Integer courseId = (Integer) map.get("courseId");
        Integer cur = (Integer) map.get("cur");
        Integer size = (Integer) map.get("size");
        Boolean star = (Boolean) map.get("star");
        if(star == null){
            star = false;
        }
        if (Validator.isNull(courseId) || Validator.isNull(cur) || Validator.isNull(size)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        if(! CourseCache.courseMap.containsKey(courseId)) {
            return Response.error(ResultCode.COURSE_NOT_EXIST_ERROR.getMsg(), ResultCode.COURSE_NOT_EXIST_ERROR.getCode());
        } else {
            return courseDataService.getDataByCourseId(courseId, cur, size, 1,star);
        }
    }

    /**
     * 获取某一课程下某人上传的资料，UID为空则意为UserId查询自己上传的资料，UID不为空意为UploadId，查询某人上传的资料
     * @param map
     * @return
     */
    @ApiOperation("获取某课程下某用户上传的资料")
    @PostMapping("/getCourseDataOfSomebody")
    public Response getCourseDataOfSomebody(@RequestBody(required = false)Map<String, Object> map) {
        int uid = 0;
        if(map.get("account") != null){
            uid = userService.getUIdByAccount((String) map.get("account"));
            if(uid == -1){
                return Response.error(ResultCode.ASSISTANT_ACCOUNT_NOT_EXIST_ERROR.getMsg(), ResultCode.ASSISTANT_ACCOUNT_NOT_EXIST_ERROR.getCode());
            }
        }
        else {
            uid = MyHandlerInterceptor.getUid();
        }
        Integer courseId = Integer.parseInt((String) map.get("courseId"));
        Integer cur = Integer.parseInt((String) map.get("cur"));
        Integer size = Integer.parseInt((String) map.get("size"));
        Boolean star = (Boolean) map.get("star");
        if (Validator.isNull(courseId) || Validator.isNull(cur) || Validator.isNull(size)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }
        if(! CourseCache.courseMap.containsKey(courseId)) {
            return Response.error(ResultCode.COURSE_NOT_EXIST_ERROR.getMsg(), ResultCode.COURSE_NOT_EXIST_ERROR.getCode());
        }
        if(star == null){
            star = false;
        }
        return courseDataService.getCourseDataOfSomebody(uid, courseId, cur, size, star);
    }

    /**
     * 更新星级
     * @param map
     * @return
     */
    @ApiOperation("更新星级")
    @PostMapping("/updateStar")
    public Response updateStar(@RequestBody Map<String,String> map){
        Integer id = Integer.parseInt(map.get("id"));
        Float star = Float.parseFloat(map.get("star"));

        if(id == null || star == null){
            return Response.error(ResultCode.PARAMETER_MISS);
        }else {
            return courseDataService.updateStar(id,star);
        }
    }
}
